import React, { useState, useEffect, useMemo, useCallback } from 'react';
import {
  Table,
  Card,
  Button,
  Space,
  Input,
  Typography,
  Tabs,
  Modal,
  PaginationProps,
  Message,
  Form,
  Skeleton,
  Select,
} from '@arco-design/web-react';
import cs from 'classnames';
import debounce from 'lodash/debounce';
import { IconPlus } from '@arco-design/web-react/icon';
import { getColumns } from './constants';
import styles from '../../style/index.module.less';
import RoleTree from './roleTree';
import RolePermissions from './rolePermission';
import {
  RoleAddUser,
  RoleDelUser,
  UserListAll,
  UserListByRoleId,
} from '@/api/modules/authentication';
import { Role, User } from '@/api/interface/authentication';
import { GlobalState } from '@/store';
import { useSelector } from 'react-redux';
import ModalTitle from '@/components/ModalTitle';

const { Search } = Input;
const { TabPane } = Tabs;
const { Option } = Select;
const { Title, Text } = Typography;
const FormItem = Form.Item;

function AuthRoles({ t, rtl }: { t: unknown; rtl: boolean }) {
  const InoperableUserRole = ['ADMIN', 'HIDDEN'];
  const NoPermissionRole = ['SUPER_ADMIN', 'ADMIN', 'HIDDEN', 'INVESTIGATOR'];
  const NoUserRole = ['MEMBER'];
  const NotRoleName = ['MEMBER', 'HIDDEN'];

  const [username, setUserName] = useState('');
  const searchChange = debounce((value) => setUserName(value), 500);

  const [role, setRole] = useState<Role>({});
  const roles = useSelector((state: GlobalState) => state.roles);
  const superAdmin = roles.filter((item) => item.level === 'SUPER_ADMIN');

  const userAction = useCallback(() => {
    if (!role.level) return false;
    if (role.level === 'SUPER_ADMIN') return false;
    if (superAdmin.length > 0 && InoperableUserRole.includes(role.level))
      return true;
    if (!InoperableUserRole.includes(role.level)) return true;
    return false;
  }, [superAdmin, role.level]);

  const [activeTab, setActiveTab] = useState('1');

  useEffect(() => {
    if (NoUserRole.includes(role.level)) return setActiveTab('2');
    setActiveTab('1');
  }, [role.id]);

  const [pagination, setPatination] = useState<PaginationProps>({
    sizeOptions: [10, 20, 50, 100],
    sizeCanChange: true,
    showTotal: true,
    pageSize: 10,
    current: 1,
    pageSizeChangeResetCurrent: true,
  });

  useEffect(() => {
    role.id && getUserList();
  }, [role.id, username, pagination.current, pagination.pageSize]);

  const deleteUser = async (record: User) => {
    Modal.warning({
      title: `${t['auth.delete.title']}`,
      content: (
        <>
          {t['auth.delete.content'] + ' '}
          <span style={{ color: 'rgb(247, 101, 96)' }}>
            {`"${record.name}"`}
          </span>
          {rtl ? ' ؟' : ' ?'}
        </>
      ),
      okButtonProps: { status: 'danger' },
      okText: `${t['auth.operations.delete']}`,
      style: { textAlign: 'center' },
      closable: true,
      onOk: async () => {
        await RoleDelUser({ roleId: role.id, userId: record.id });
        Message.success(t['auth.delete.success']);
        getUserList();
      },
    });
  };

  const columns = useMemo(
    () => getColumns(t, deleteUser, userAction()),
    [t, deleteUser, userAction]
  );

  const [userList, setUserList] = useState<User[]>([]);

  const [loading, setLoading] = useState(false);

  const getUserList = async () => {
    const { current, pageSize } = pagination;
    setLoading(true);
    setUserList([]);
    try {
      const { data } = await UserListByRoleId({
        roleId: role.id,
        name: username,
        pageNo: current,
        pageSize,
      });
      setUserList(data.data);
      setPatination({
        ...pagination,
        current,
        pageSize,
        total: data.count,
      });
    } finally {
      setLoading(false);
    }
  };

  function onChangeTable({ current, pageSize }) {
    setPatination({
      ...pagination,
      current,
      pageSize,
    });
  }

  const [form] = Form.useForm();
  const [userAll, setUserAll] = useState<User[]>([]);
  const [visible, setVisible] = useState(false);
  const [userLoading, setUserLoading] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);

  const addUser = async () => {
    try {
      setVisible(true);
      setUserLoading(true);
      form.resetFields();
      const { data } = await UserListAll({ name: '' });
      // const userFilter = data.filter((item) => {
      //   if (item.roles) {
      //     return !item.roles.some((role) => NotRoleName.includes(role.level));
      //   }
      //   return true;
      // });
      setUserAll(data);
    } finally {
      setUserLoading(false);
    }
  };

  const onSubmit = () => {
    form.validate(async (errors, values) => {
      if (errors) return;
      try {
        setConfirmLoading(true);
        const user = userAll.find((item) => item.account === values.account);
        await RoleAddUser({
          roleId: role.id,
          userId: user.id,
          name: user.name,
          account: user.account,
          email: user.email,
          phone: user.phone,
        });
        Message.success(t['auth.save.success']);
        setVisible(false);
        getUserList();
      } finally {
        setConfirmLoading(false);
      }
    });
  };

  return (
    <div className={cs(styles['auth-roles'], rtl ? 'rtl' : '')}>
      <Card className={styles['role-tree']}>
        <RoleTree t={t} rtl={rtl} role={role} setRole={setRole} />
      </Card>

      <Card className={styles['role-table']}>
        {role.name && (
          <div className={cs(styles['table-title'])}>
            <Title heading={5}>
              {role[rtl ? 'nameAr' : 'name'] || role['name']}
            </Title>
            <Text className="ltr">
              {role[rtl ? 'descriptionAr' : 'description'] ||
                role['description']}
            </Text>
          </div>
        )}

        <Tabs key="card" activeTab={activeTab} onClickTab={setActiveTab}>
          {!NoUserRole.includes(role.level) && (
            <TabPane key="1" title={t['auth.tabs.user']}>
              <div className={styles['button-group']}>
                <Space>
                  <Search
                    allowClear
                    placeholder={t['auth.input.placeholder.username']}
                    style={{ width: 350 }}
                    onChange={searchChange}
                  />
                </Space>
                <Space>
                  {userAction() && (
                    <Button
                      type="primary"
                      icon={<IconPlus />}
                      onClick={() => addUser()}
                    >
                      {t['auth.operations.add.user']}
                    </Button>
                  )}
                </Space>
              </div>
              <Table
                border={{ wrapper: true, cell: true }}
                rowKey="id"
                loading={loading}
                onChange={onChangeTable}
                pagination={pagination}
                columns={columns}
                data={userList}
              />
            </TabPane>
          )}

          {!NoPermissionRole.includes(role.level) && (
            <TabPane key="2" title={t['auth.tabs.permission']}>
              <RolePermissions t={t} role={role} />
            </TabPane>
          )}
        </Tabs>
      </Card>

      {/* add user modal */}
      <Modal
        title={<ModalTitle title={t['auth.operations.add.user']} />}
        visible={visible}
        onCancel={() => setVisible(false)}
        onOk={() => onSubmit()}
        confirmLoading={confirmLoading}
        okText={t['auth.operations.add.user']}
        cancelText={t['auth.operations.cancel']}
      >
        <Skeleton text={{ rows: 2 }} loading={userLoading}>
          <Form
            autoComplete="off"
            form={form}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
          >
            <FormItem
              field="account"
              label={t['auth.tabs.user']}
              rules={[
                { required: true, message: t['auth.select.placeholder.user'] },
              ]}
            >
              <Select
                placeholder={t['auth.select.placeholder.user']}
                allowClear
                showSearch
                filterOption={(inputValue, option) => {
                  // return option.props.children[0] === inputValue;
                  return (
                    option.props.children
                      .join('')
                      .toLowerCase()
                      .indexOf(inputValue.toLowerCase()) >= 0
                  );
                }}
              >
                {userAll.map((item) => {
                  const filteredRoles = item.roles?.filter(
                    (roleItem) =>
                      !NotRoleName.some((role) => role === roleItem.level)
                  );

                  return (
                    <Option key={item.account} value={item.account}>
                      {item.name} {`(${item.employeeId}`}
                      {filteredRoles?.length
                        ? `, ${filteredRoles
                            .map((roleItem) => roleItem.name)
                            .join(', ')})`
                        : ')'}
                    </Option>
                  );
                })}
              </Select>
            </FormItem>
          </Form>
        </Skeleton>
      </Modal>
    </div>
  );
}

export default AuthRoles;
